<?php
namespace app\login\controller;

use think\Controller;
use app\common\controller\Common;
use app\common\model\User;
use app\common\model\UserWx;
use think\Db;

/**
 * 微信小程序登录
 **/
class WxMiniprogramLogin extends Controller
{
    private $wxAppid;
    private $wxAppSecret;
    
    private $code2SessionUrl; // 登录凭证校验URL
    
    public function __construct() {
        parent::__construct();
        $this->wxAppid = config('custom.wxAppid');
        $this->wxAppSecret = config('custom.wxAppSecret');
        
        $this->commonCtl = new Common();
        
        $this->userModel = new \app\common\model\User();
        $this->wxUserModel = new \app\common\model\UserWx();
    }
    
    public function index()
    {
        return '访问错误';
        exit;
    }
    
    // 生成登录凭证校验URL
    private function makeCode2SessionUrl($code = '') {
        $this->code2SessionUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->wxAppid . '&secret=' . $this->wxAppSecret . '&js_code=' . $code . '&grant_type=authorization_code';
    }
    
    // 整理post过来的userinfo参数
    private function mergeUrlWxUserInfo($userInfo) {
        $res = array();
        foreach ($userInfo as $v){
            $res[$v[0]] = $v[1];
        }
        return $res;
    }
    
    // step1: 从小程序获取code
    // step2: 向微信api请求session_key和openid
    // step3: 判断用户是否存在，存在-登录，不存在-新增 
   
    // step1
    public function wxminiprogramLogin($code, $userInfo) {
        $res = array();
        $res['status'] = 250;
        $res['txt'] = '';
        $res['data']['userId'] = 0;
        
        if(!empty($code)){
            // step2
            $this->makeCode2SessionUrl($code);
            $auth_res = $this->commonCtl->commonCurlGet($this->code2SessionUrl);

            // step3
            if(!isset($auth_res['errcode'])){
                $userId = $this->wxUserModel->where('openid', $auth_res['openid'])->value('user_id');
                $mergeWxUserInfo = $this->mergeUrlWxUserInfo($userInfo);

                if($userId === null){
                    // 新增注册微信用户
                    $mergeWxUserInfo['ctime'] = time();
                    $mergeWxUserInfo['openid'] = $auth_res['openid'];
                    $res = $this->wxUserModel->registerWxUser($mergeWxUserInfo);
                }else{
                    // 更新用户信息，不强制更新成功
                    $this->wxUserModel->updateWxUser($userId, $mergeWxUserInfo);
                    $res['data']['userId'] = $userId;
                    $res['status'] = 200;
                    $res['txt'] = lang('login success');
                }
            }else{
                $res['txt'] = $auth_res['errmsg'];
            }
        }else{
            $res['txt'] = lang('wrong code');
        }
        
        return $res;
    }
    
    
}
